package com.lingnan.blog.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lingnan.blog.entity.*;
import com.lingnan.blog.service.ArticleService;
import com.lingnan.blog.service.CollectService;
import com.lingnan.blog.service.ViewService;
import com.lingnan.blog.utils.DateUtil;
import com.lingnan.blog.utils.QiniuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * web处理层
 *
 * @author HeGuanChao
 */
@Controller
@RequestMapping(value = {"/article", "/interview"})
public class ArticlesController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private ViewService viewService;
    @Autowired
    private CollectService collectService;
    @Autowired
    private QiniuUtil qiniuUtil;
    @Autowired
    HttpSession session;


    /**
     * 保存（发布/更新）文章
     *
     * @param article
     * @param model
     * @return
     */
    @PostMapping("/edit")
    public String edit(Article article, @RequestParam("file") MultipartFile file, RedirectAttributes model) {
        try {
            //判断文章id是否不存在
            if (StringUtils.isEmpty(article.getId())) {
                //保存封面图片
                article.setCover("http://" + qiniuUtil.upload(file));
                //保存文章
                articleService.save(article);

                //保存到浏览记录表
                View view = new View();
                view.setUId(String.valueOf(article.getUId()));
                view.setAId(article.getId());
                view.setTime(DateUtil.format(new Date()));
                viewService.insertSelective(view);

                //返回信息
                model.addFlashAttribute("msg", "发布成功");
            } else {
                //保存封面图片
                article.setCover("http://" + qiniuUtil.upload(file));
                //id存在则为更新数据
                //修改文章
                articleService.update(article);
                //修改成功
                model.addFlashAttribute("msg", "更新成功");
            }
            return "redirect:/article/" + article.getId();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 文章收藏
     */
    @PostMapping("/collect")
    public @ResponseBody
    Result collectArticle(Integer id) {
        try {
            //0. 判断用户是否登录，没有登录不能收藏
            User loginUser = (User) session.getAttribute("loginUser");
            //1. 根据文章id查询文章的收藏总数
            int collects = articleService.findByCollects(id);

            //判断用户是否登录了
            if (loginUser == null) {
                return new Result(false, "请登录", collects);
            }

            //判断用户是否点赞过了文章
            Collect collect = collectService.findByUidAndAid(loginUser.getId(), id);
            if (collect != null) {
                return new Result(false, "您已经收藏过了文章", collects);
            }

            //2. 更新文章的收藏总数
            articleService.updateCollects(id, collects + 1);
            //3. 记录哪个用户收藏了文章
            collectService.saveSelective(new Collect(null, loginUser.getId(), id,
                    DateUtil.format(new Date())));
            return new Result(true, "收藏成功", collects + 1);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/offCollect")
    public @ResponseBody
    Result offCollect(Integer id) {
        try {
            //0. 判断用户是否登录，没有登录不能收藏
            User loginUser = (User) session.getAttribute("loginUser");
            //1. 根据文章id查询文章的收藏总数
            int collects = articleService.findByCollects(id);

            //2. 更新文章的收藏总数 - 1
            articleService.updateCollects(id, collects - 1);
            //3. 删除当前用户的收藏记录
            collectService.removeByUidAndAid(loginUser.getId(), id);
            return new Result(true, "你取消收藏了", collects - 1);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/upload")
    public @ResponseBody
    String fileUpload(@RequestParam("file") MultipartFile file) {
        try {
            return new ObjectMapper().writeValueAsString("http://" + qiniuUtil.upload(file));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}
